package com.binvshe.binvshe.mine.corporation.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.account.utils.FragmentUtils;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.mine.FollowState;
import com.binvshe.binvshe.mine.follow.bean.FollowPersonBean;
import com.pachong.android.baseuicomponent.CompState;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * A simple {@link Fragment} subclass.
 * 好友列表
 */
public class FriendsFragment extends SwipeListFragment {

    private static final String KEY_CLUB_ID = "key_club_id";
    private int mClubId;
    private int mPage = 0;

    public static FriendsFragment newInstance(int clubId) {
        Bundle args = new Bundle();
        args.putInt(KEY_CLUB_ID, clubId);
        FriendsFragment fragment = new FriendsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mClubId = getArguments().getInt(KEY_CLUB_ID);
        showToolbar();
        getCustomToolbar().enableBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentUtils.backStack(getActivity());
            }
        });
        setTitle("邀请好友");
        startLoading();
        return view;
    }

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        mPage = 0;
        getAdapter().getData().clear();
        startLoading();
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new FriendsListAdapter(getContext());
    }

    @Override
    public void onStartLoading() {
        getDataList();
        if (getData().size() > 0) {
            setState(CompState.DATA);
        } else {
            setState(CompState.EMPTY);
        }
    }

    DataRequestListener response = new DataRequestListener<List<FollowPersonBean>>(FollowPersonBean.class) {
        @Override
        public void onStart(Context context, String url) {

            enableProgress(false);
            super.onStart(context, url);
        }

        @Override
        public void onSuccess(List<FollowPersonBean> o) {
            super.onSuccess(o);
            for (FollowPersonBean bean : o) {
                switch (bean.getFollow_state()) {
                    case FollowState.EACH_FOLLOW:
                        getAdapter().getData().add(bean);
                        setState(CompState.DATA);
                        break;
                }
            }
            getAdapter().notifyDataSetChanged();
        }

        @Override
        public void onFailure(Throwable t, int errorNo, String strMsg) {
            super.onFailure(t, errorNo, strMsg);
        }
    };

    public boolean hasmore(JSONObject dataJsonObj) {
        JSONObject jobj = dataJsonObj;
        if (jobj != null) {
            int pageNo = jobj.optInt("page_no"); // default 0
            int totalPages = jobj.optInt("total_pages"); // default 0
            return pageNo < totalPages ? true : false;
        }
        return true;
    }

    public void getDataList() {
        if (mPage == 0 || hasmore(response.getResponseDataParser().getDataJsonObj())) {
            mPage++;
            IHttpRequest request = new MyHttpRequest(getContext());
            UrlParams urlParams = new UrlParams();
            urlParams.put(ParamKey.PAGE, mPage + "");
            urlParams.put(ParamKey.SIZE, 8 + "");
            request.get(UrlCenter.USER_FOLLOW, urlParams, response);
        }
    }


    public class FriendsListAdapter extends RecyclerViewBaseAdapter<FollowPersonBean> {

        public FriendsListAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new VH(setAdapterViewItem(parent, R.layout.item_invite_friends));
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, final int position) {
            final VH viewHolder = (VH) holder;
            final FollowPersonBean followPersonBean = getData().get(position);
            if (!TextUtils.isEmpty(followPersonBean.getPortrait()))
                IML.load(getActivity(), viewHolder.mCirHead, followPersonBean.getPortrait());
            if (!TextUtils.isEmpty(followPersonBean.getNick_name()))
                viewHolder.mTvName.setText(followPersonBean.getNick_name());
            viewHolder.mBtnInvite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyHttpRequest request = new MyHttpRequest(getContext());
                    String url = String.format(UrlCenter.INVITE_CLUB, mClubId, followPersonBean.getUser_id());
                    JSONObject jobj = new JSONObject();
                    try {
                        jobj.put(ParamKey.Club.REASON, "理由");
                        request.post(url, jobj, new DataRequestListener<String>(String.class) {

                            @Override
                            public void onStart(Context context, String url) {
                                enableProgress(false);
                                super.onStart(context, url);
                            }

                            @Override
                            public void onSuccess(String o) {
                                super.onSuccess(o);
                                EasyToast.showToast(getContext(), "邀请 " + followPersonBean.getNick_name() + " 成功~");
                                viewHolder.mBtnInvite.setEnabled(false);
                                viewHolder.mBtnInvite.setText("已邀请");
                            }

                            @Override
                            public void onFailure(Throwable t, int errorNo, String strMsg) {
                                super.onFailure(t, errorNo, strMsg);
                                EasyToast.showToast(getContext(), strMsg);
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public class VH extends RecyclerView.ViewHolder {

        @Bind(R.id.mCirHead)
        CircleImageView mCirHead;
        @Bind(R.id.mTvName)
        TextView mTvName;
        @Bind(R.id.mBtnInvite)
        Button mBtnInvite;

        public VH(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
